[[...path]].page.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. import type React from 'react';
  2. import type { JSX, ReactNode } from 'react';
  3. import { useEffect } from 'react';
  4. import type { GetServerSideProps, GetServerSidePropsContext } from 'next';
  5. import dynamic from 'next/dynamic';
  6. import Head from 'next/head';
  7. import { useRouter } from 'next/router';
  8. import type {
  9. IDataWithMeta,
  10. IPageInfo,
  11. IPagePopulatedToShowRevision,
  12. } from '@growi/core';
  13. import { isIPageInfo } from '@growi/core';
  14. import { isClient, pagePathUtils, pathUtils } from '@growi/core/dist/utils';
  15. import EventEmitter from 'events';
  16. import ExtensibleCustomError from 'extensible-custom-error';
  17. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  18. import superjson from 'superjson';
  19. import { BasicLayout } from '~/components/Layout/BasicLayout';
  20. import { PageView } from '~/components/PageView/PageView';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  22. import {
  23. SupportedAction,
  24. type SupportedActionType,
  25. } from '~/interfaces/activity';
  26. import type { CrowiRequest } from '~/interfaces/crowi-request';
  27. import { RegistrationMode } from '~/interfaces/registration-mode';
  28. import type { RendererConfig } from '~/interfaces/services/renderer';
  29. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  30. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  31. import type { PageDocument, PageModel } from '~/server/models/page';
  32. import type { PageRedirectModel } from '~/server/models/page-redirect';
  33. import { useEditorModeClassName } from '~/services/layout/use-editor-mode-class-name';
  34. import { useEditingMarkdown } from '~/stores/editor';
  35. import {
  36. useCurrentPageId,
  37. useIsLatestRevision,
  38. useIsNotFound,
  39. useSWRMUTxCurrentPage,
  40. useSWRxCurrentPage,
  41. useTemplateBodyData,
  42. useTemplateTagData,
  43. } from '~/stores/page';
  44. import { useRedirectFrom } from '~/stores/page-redirect';
  45. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  46. import {
  47. useSetupGlobalSocket,
  48. useSetupGlobalSocketForPage,
  49. } from '~/stores/websocket';
  50. import {
  51. useCurrentPageYjsData,
  52. useSWRMUTxCurrentPageYjsData,
  53. } from '~/stores/yjs';
  54. import {
  55. useCsrfToken,
  56. useCurrentPathname,
  57. useCurrentUser,
  58. useDefaultIndentSize,
  59. useDisableLinkSharing,
  60. useElasticsearchMaxBodyLengthToIndex,
  61. useGrowiCloudUri,
  62. useIsAclEnabled,
  63. useIsAiEnabled,
  64. useIsAllReplyShown,
  65. useIsBulkExportPagesEnabled,
  66. useIsContainerFluid,
  67. useIsEnabledAttachTitleHeader,
  68. useIsEnabledMarp,
  69. useIsEnabledStaleNotification,
  70. useIsForbidden,
  71. useIsGuestUser,
  72. useIsIdenticalPath,
  73. useIsIndentSizeForced,
  74. useIsLocalAccountRegistrationEnabled,
  75. useIsNotCreatable,
  76. useIsPdfBulkExportEnabled,
  77. useIsRomUserAllowedToComment,
  78. useIsSearchPage,
  79. useIsSearchScopeChildrenAsDefault,
  80. useIsSearchServiceConfigured,
  81. useIsSearchServiceReachable,
  82. useIsSharedUser,
  83. useIsSlackConfigured,
  84. useIsUploadAllFileAllowed,
  85. useIsUploadEnabled,
  86. useIsUsersHomepageDeletionEnabled,
  87. useLimitLearnablePageCountPerAssistant,
  88. useRendererConfig,
  89. useShowPageSideAuthors,
  90. } from '~/stores-universal/context';
  91. import loggerFactory from '~/utils/logger';
  92. import type { NextPageWithLayout } from './_app.page';
  93. import type { CommonProps } from './utils/commons';
  94. import {
  95. addActivity,
  96. generateCustomTitleForPage,
  97. getNextI18NextConfig,
  98. getServerSideCommonProps,
  99. skipSSR,
  100. useInitSidebarConfig,
  101. } from './utils/commons';
  102. declare global {
  103. // eslint-disable-next-line vars-on-top, no-var
  104. var globalEmitter: EventEmitter;
  105. }
  106. const GrowiContextualSubNavigationSubstance = dynamic(
  107. () => import('~/client/components/Navbar/GrowiContextualSubNavigation'),
  108. { ssr: false },
  109. );
  110. const GrowiPluginsActivator = dynamic(
  111. () =>
  112. import('~/features/growi-plugin/client/components').then(
  113. (mod) => mod.GrowiPluginsActivator,
  114. ),
  115. { ssr: false },
  116. );
  117. const DisplaySwitcher = dynamic(
  118. () =>
  119. import('~/client/components/Page/DisplaySwitcher').then(
  120. (mod) => mod.DisplaySwitcher,
  121. ),
  122. { ssr: false },
  123. );
  124. const PageStatusAlert = dynamic(
  125. () =>
  126. import('~/client/components/PageStatusAlert').then(
  127. (mod) => mod.PageStatusAlert,
  128. ),
  129. { ssr: false },
  130. );
  131. const UnsavedAlertDialog = dynamic(
  132. () => import('~/client/components/UnsavedAlertDialog'),
  133. { ssr: false },
  134. );
  135. const DescendantsPageListModal = dynamic(
  136. () =>
  137. import('~/client/components/DescendantsPageListModal').then(
  138. (mod) => mod.DescendantsPageListModal,
  139. ),
  140. { ssr: false },
  141. );
  142. const DrawioModal = dynamic(
  143. () =>
  144. import('~/client/components/PageEditor/DrawioModal').then(
  145. (mod) => mod.DrawioModal,
  146. ),
  147. { ssr: false },
  148. );
  149. const HandsontableModal = dynamic(
  150. () =>
  151. import('~/client/components/PageEditor/HandsontableModal').then(
  152. (mod) => mod.HandsontableModal,
  153. ),
  154. { ssr: false },
  155. );
  156. const TemplateModal = dynamic(
  157. () =>
  158. import('~/client/components/TemplateModal').then(
  159. (mod) => mod.TemplateModal,
  160. ),
  161. { ssr: false },
  162. );
  163. const LinkEditModal = dynamic(
  164. () =>
  165. import('~/client/components/PageEditor/LinkEditModal').then(
  166. (mod) => mod.LinkEditModal,
  167. ),
  168. { ssr: false },
  169. );
  170. const TagEditModal = dynamic(
  171. () =>
  172. import('~/client/components/PageTags/TagEditModal').then(
  173. (mod) => mod.TagEditModal,
  174. ),
  175. { ssr: false },
  176. );
  177. const ConflictDiffModal = dynamic(
  178. () =>
  179. import('~/client/components/PageEditor/ConflictDiffModal').then(
  180. (mod) => mod.ConflictDiffModal,
  181. ),
  182. { ssr: false },
  183. );
  184. const EditablePageEffects = dynamic(
  185. () =>
  186. import('~/client/components/Page/EditablePageEffects').then(
  187. (mod) => mod.EditablePageEffects,
  188. ),
  189. { ssr: false },
  190. );
  191. const logger = loggerFactory('growi:pages:all');
  192. const { isPermalink: _isPermalink, isCreatablePage } = pagePathUtils;
  193. const { removeHeadingSlash } = pathUtils;
  194. type IPageToShowRevisionWithMeta = IDataWithMeta<
  195. IPagePopulatedToShowRevision & PageDocument,
  196. IPageInfo
  197. >;
  198. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  199. superjson.registerCustom<
  200. IPageToShowRevisionWithMeta,
  201. IPageToShowRevisionWithMetaSerialized
  202. >(
  203. {
  204. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  205. return v?.data != null && v?.data.toObject != null && isIPageInfo(v.meta);
  206. },
  207. serialize: (v) => {
  208. return {
  209. data: superjson.stringify(v.data.toObject()),
  210. meta: superjson.stringify(v.meta),
  211. };
  212. },
  213. deserialize: (v) => {
  214. return {
  215. data: superjson.parse(v.data),
  216. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  217. };
  218. },
  219. },
  220. 'IPageToShowRevisionWithMetaTransformer',
  221. );
  222. // GrowiContextualSubNavigation for NOT shared page
  223. type GrowiContextualSubNavigationProps = {
  224. isLinkSharingDisabled: boolean;
  225. };
  226. const GrowiContextualSubNavigation = (
  227. props: GrowiContextualSubNavigationProps,
  228. ): JSX.Element => {
  229. const { isLinkSharingDisabled } = props;
  230. const { data: currentPage } = useSWRxCurrentPage();
  231. return (
  232. <GrowiContextualSubNavigationSubstance
  233. currentPage={currentPage}
  234. isLinkSharingDisabled={isLinkSharingDisabled}
  235. />
  236. );
  237. };
  238. type Props = CommonProps & {
  239. pageWithMeta: IPageToShowRevisionWithMeta | null;
  240. // pageUser?: any,
  241. redirectFrom?: string;
  242. // shareLinkId?: string;
  243. isLatestRevision?: boolean;
  244. isIdenticalPathPage?: boolean;
  245. isForbidden: boolean;
  246. isNotFound: boolean;
  247. isNotCreatable: boolean;
  248. // isAbleToDeleteCompletely: boolean,
  249. templateTagData?: string[];
  250. templateBodyData?: string;
  251. isLocalAccountRegistrationEnabled: boolean;
  252. isSearchServiceConfigured: boolean;
  253. isSearchServiceReachable: boolean;
  254. isSearchScopeChildrenAsDefault: boolean;
  255. elasticsearchMaxBodyLengthToIndex: number;
  256. isEnabledMarp: boolean;
  257. isRomUserAllowedToComment: boolean;
  258. sidebarConfig: ISidebarConfig;
  259. isSlackConfigured: boolean;
  260. // isMailerSetup: boolean,
  261. isAclEnabled: boolean;
  262. // hasSlackConfig: boolean,
  263. drawioUri: string | null;
  264. // highlightJsStyle: string,
  265. isAllReplyShown: boolean;
  266. showPageSideAuthors: boolean;
  267. isContainerFluid: boolean;
  268. isUploadEnabled: boolean;
  269. isUploadAllFileAllowed: boolean;
  270. isBulkExportPagesEnabled: boolean;
  271. isPdfBulkExportEnabled: boolean;
  272. isEnabledStaleNotification: boolean;
  273. isEnabledAttachTitleHeader: boolean;
  274. // isEnabledLinebreaks: boolean,
  275. // isEnabledLinebreaksInComments: boolean,
  276. adminPreferredIndentSize: number;
  277. isIndentSizeForced: boolean;
  278. disableLinkSharing: boolean;
  279. skipSSR: boolean;
  280. ssrMaxRevisionBodyLength: number;
  281. yjsData: CurrentPageYjsData;
  282. rendererConfig: RendererConfig;
  283. aiEnabled: boolean;
  284. limitLearnablePageCountPerAssistant: number;
  285. isUsersHomepageDeletionEnabled: boolean;
  286. };
  287. const Page: NextPageWithLayout<Props> = (props: Props) => {
  288. // register global EventEmitter
  289. if (isClient() && window.globalEmitter == null) {
  290. window.globalEmitter = new EventEmitter();
  291. }
  292. const router = useRouter();
  293. useCurrentUser(props.currentUser ?? null);
  294. // commons
  295. useCsrfToken(props.csrfToken);
  296. useGrowiCloudUri(props.growiCloudUri);
  297. // page
  298. useIsContainerFluid(props.isContainerFluid);
  299. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  300. useIsForbidden(props.isForbidden);
  301. useIsNotCreatable(props.isNotCreatable);
  302. useRedirectFrom(props.redirectFrom ?? null);
  303. useIsSharedUser(false); // this page cann't be routed for '/share'
  304. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  305. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  306. useIsSearchPage(false);
  307. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  308. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  309. useIsSearchServiceReachable(props.isSearchServiceReachable);
  310. useElasticsearchMaxBodyLengthToIndex(props.elasticsearchMaxBodyLengthToIndex);
  311. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  312. useIsSlackConfigured(props.isSlackConfigured);
  313. // useIsMailerSetup(props.isMailerSetup);
  314. useIsAclEnabled(props.isAclEnabled);
  315. // useHasSlackConfig(props.hasSlackConfig);
  316. useDefaultIndentSize(props.adminPreferredIndentSize);
  317. useIsIndentSizeForced(props.isIndentSizeForced);
  318. useDisableLinkSharing(props.disableLinkSharing);
  319. useRendererConfig(props.rendererConfig);
  320. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  321. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  322. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  323. useIsAllReplyShown(props.isAllReplyShown);
  324. useShowPageSideAuthors(props.showPageSideAuthors);
  325. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  326. useIsUploadEnabled(props.isUploadEnabled);
  327. useIsBulkExportPagesEnabled(props.isBulkExportPagesEnabled);
  328. useIsPdfBulkExportEnabled(props.isPdfBulkExportEnabled);
  329. useIsLocalAccountRegistrationEnabled(props.isLocalAccountRegistrationEnabled);
  330. useIsRomUserAllowedToComment(props.isRomUserAllowedToComment);
  331. useIsAiEnabled(props.aiEnabled);
  332. useLimitLearnablePageCountPerAssistant(
  333. props.limitLearnablePageCountPerAssistant,
  334. );
  335. useIsUsersHomepageDeletionEnabled(props.isUsersHomepageDeletionEnabled);
  336. const { pageWithMeta } = props;
  337. const pageId = pageWithMeta?.data._id;
  338. const revisionId = pageWithMeta?.data.revision?._id;
  339. const revisionBody = pageWithMeta?.data.revision?.body;
  340. useCurrentPathname(props.currentPathname);
  341. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  342. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  343. const { trigger: mutateCurrentPageYjsDataFromApi } =
  344. useSWRMUTxCurrentPageYjsData();
  345. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  346. const { data: currentPageId, mutate: mutateCurrentPageId } =
  347. useCurrentPageId();
  348. const { data: isGuestUser } = useIsGuestUser();
  349. const { mutate: mutateIsNotFound } = useIsNotFound();
  350. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  351. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  352. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  353. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  354. const { mutate: mutateCurrentPageYjsData } = useCurrentPageYjsData();
  355. useSetupGlobalSocket();
  356. useSetupGlobalSocketForPage(pageId);
  357. // Store initial data (When revisionBody is not SSR)
  358. useEffect(() => {
  359. if (!props.skipSSR) {
  360. return;
  361. }
  362. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  363. const mutatePageData = async () => {
  364. const pageData = await mutateCurrentPage();
  365. mutateEditingMarkdown(pageData?.revision?.body);
  366. };
  367. // If skipSSR is true, use the API to retrieve page data.
  368. // Because pageWIthMeta does not contain revision.body
  369. mutatePageData();
  370. }
  371. }, [
  372. revisionId,
  373. currentPageId,
  374. mutateCurrentPage,
  375. mutateEditingMarkdown,
  376. props.isNotFound,
  377. props.skipSSR,
  378. ]);
  379. // Load current yjs data
  380. useEffect(() => {
  381. if (
  382. !isGuestUser &&
  383. currentPageId != null &&
  384. revisionId != null &&
  385. mutateCurrentPageYjsDataFromApi != null &&
  386. !props.isNotFound
  387. ) {
  388. mutateCurrentPageYjsDataFromApi();
  389. }
  390. }, [
  391. isGuestUser,
  392. currentPageId,
  393. mutateCurrentPageYjsDataFromApi,
  394. props.isNotFound,
  395. revisionId,
  396. ]);
  397. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  398. useEffect(() => {
  399. const decodedURI = decodeURI(window.location.pathname);
  400. if (isClient() && decodedURI !== props.currentPathname) {
  401. const { search, hash } = window.location;
  402. router.replace(`${props.currentPathname}${search}${hash}`, undefined, {
  403. shallow: true,
  404. });
  405. }
  406. }, [props.currentPathname, router]);
  407. // initialize mutateEditingMarkdown only once per page
  408. // need to include useCurrentPathname not useCurrentPagePath
  409. useEffect(() => {
  410. if (props.currentPathname != null) {
  411. mutateEditingMarkdown(revisionBody);
  412. }
  413. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  414. useEffect(() => {
  415. mutateRemoteRevisionId(revisionId);
  416. }, [mutateRemoteRevisionId, revisionId]);
  417. useEffect(() => {
  418. mutateCurrentPageId(pageId ?? null);
  419. }, [mutateCurrentPageId, pageId]);
  420. useEffect(() => {
  421. mutateIsNotFound(props.isNotFound);
  422. }, [mutateIsNotFound, props.isNotFound]);
  423. useEffect(() => {
  424. mutateIsLatestRevision(props.isLatestRevision);
  425. }, [mutateIsLatestRevision, props.isLatestRevision]);
  426. useEffect(() => {
  427. mutateTemplateTagData(props.templateTagData);
  428. }, [props.templateTagData, mutateTemplateTagData]);
  429. useEffect(() => {
  430. mutateTemplateBodyData(props.templateBodyData);
  431. }, [props.templateBodyData, mutateTemplateBodyData]);
  432. useEffect(() => {
  433. mutateCurrentPageYjsData(props.yjsData);
  434. }, [mutateCurrentPageYjsData, props.yjsData]);
  435. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  436. // So preferentially take page data from useSWRxCurrentPage
  437. const pagePath =
  438. currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  439. const title = generateCustomTitleForPage(props, pagePath);
  440. return (
  441. <>
  442. <Head>
  443. <title>{title}</title>
  444. </Head>
  445. <div className="dynamic-layout-root justify-content-between">
  446. <GrowiContextualSubNavigation
  447. isLinkSharingDisabled={props.disableLinkSharing}
  448. />
  449. <PageView
  450. className="d-edit-none"
  451. pagePath={pagePath}
  452. initialPage={pageWithMeta?.data}
  453. rendererConfig={props.rendererConfig}
  454. />
  455. <EditablePageEffects />
  456. <DisplaySwitcher />
  457. <PageStatusAlert />
  458. </div>
  459. </>
  460. );
  461. };
  462. const BasicLayoutWithEditor = ({
  463. children,
  464. }: {
  465. children?: ReactNode;
  466. }): JSX.Element => {
  467. const editorModeClassName = useEditorModeClassName();
  468. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  469. };
  470. type LayoutProps = Props & {
  471. children?: ReactNode;
  472. };
  473. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  474. // init sidebar config with UserUISettings and sidebarConfig
  475. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  476. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  477. };
  478. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  479. return (
  480. <>
  481. <GrowiPluginsActivator />
  482. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  483. <Layout {...page.props}>{page}</Layout>
  484. <UnsavedAlertDialog />
  485. <DescendantsPageListModal />
  486. <DrawioModal />
  487. <HandsontableModal />
  488. <TemplateModal />
  489. <LinkEditModal />
  490. <TagEditModal />
  491. <ConflictDiffModal />
  492. </>
  493. );
  494. };
  495. function getPageIdFromPathname(currentPathname: string): string | null {
  496. return _isPermalink(currentPathname)
  497. ? removeHeadingSlash(currentPathname)
  498. : null;
  499. }
  500. class MultiplePagesHitsError extends ExtensibleCustomError {
  501. pagePath: string;
  502. constructor(pagePath: string) {
  503. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  504. this.pagePath = pagePath;
  505. }
  506. }
  507. async function injectPageData(
  508. context: GetServerSidePropsContext,
  509. props: Props,
  510. ): Promise<void> {
  511. const { model: mongooseModel } = await import('mongoose');
  512. const req: CrowiRequest = context.req as CrowiRequest;
  513. const { crowi } = req;
  514. const { revisionId } = req.query;
  515. const Page = crowi.model('Page') as PageModel;
  516. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  517. const { pageService, configManager } = crowi;
  518. let currentPathname = props.currentPathname;
  519. const pageId = getPageIdFromPathname(currentPathname);
  520. const isPermalink = _isPermalink(currentPathname);
  521. const { user } = req;
  522. if (!isPermalink) {
  523. // check redirects
  524. const chains =
  525. await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  526. if (chains != null) {
  527. // overwrite currentPathname
  528. currentPathname = chains.end.toPath;
  529. props.currentPathname = currentPathname;
  530. // set redirectFrom
  531. props.redirectFrom = chains.start.fromPath;
  532. }
  533. // check whether the specified page path hits to multiple pages
  534. const count = await Page.countByPathAndViewer(
  535. currentPathname,
  536. user,
  537. null,
  538. true,
  539. );
  540. if (count > 1) {
  541. throw new MultiplePagesHitsError(currentPathname);
  542. }
  543. }
  544. const pageWithMeta = await pageService.findPageAndMetaDataByViewer(
  545. pageId,
  546. currentPathname,
  547. user,
  548. true,
  549. ); // includeEmpty = true, isSharedPage = false
  550. const { data: page, meta } = pageWithMeta ?? {};
  551. // add user to seen users
  552. if (page != null && user != null) {
  553. await page.seen(user);
  554. }
  555. props.pageWithMeta = null;
  556. // populate & check if the revision is latest
  557. if (page != null) {
  558. page.initLatestRevisionField(revisionId);
  559. props.isLatestRevision = page.isLatestRevision();
  560. const ssrMaxRevisionBodyLength = configManager.getConfig(
  561. 'app:ssrMaxRevisionBodyLength',
  562. );
  563. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  564. const populatedPage = await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  565. props.pageWithMeta = {
  566. data: populatedPage,
  567. meta,
  568. };
  569. }
  570. }
  571. async function injectRoutingInformation(
  572. context: GetServerSidePropsContext,
  573. props: Props,
  574. ): Promise<void> {
  575. const req: CrowiRequest = context.req as CrowiRequest;
  576. const { crowi } = req;
  577. const Page = crowi.model('Page') as PageModel;
  578. const { currentPathname } = props;
  579. const pageId = getPageIdFromPathname(currentPathname);
  580. const isPermalink = _isPermalink(currentPathname);
  581. const page = props.pageWithMeta?.data;
  582. if (props.isIdenticalPathPage) {
  583. props.isNotCreatable = true;
  584. } else if (page == null) {
  585. props.isNotFound = true;
  586. props.isNotCreatable = !isCreatablePage(currentPathname);
  587. // check the page is forbidden or just does not exist.
  588. const count = isPermalink
  589. ? await Page.count({ _id: pageId })
  590. : await Page.count({ path: currentPathname });
  591. props.isForbidden = count > 0;
  592. } else {
  593. props.isNotFound = page.isEmpty;
  594. props.isNotCreatable = false;
  595. props.isForbidden = false;
  596. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  597. if (isPermalink && page.isEmpty) {
  598. props.currentPathname = page.path;
  599. }
  600. // /path/to/page ==> /62a88db47fed8b2d94f30000
  601. if (!isPermalink && !page.isEmpty) {
  602. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  603. if (!isToppage) {
  604. props.currentPathname = `/${page._id}`;
  605. }
  606. }
  607. if (!props.skipSSR) {
  608. props.yjsData = await crowi.pageService.getYjsData(page._id.toString());
  609. }
  610. }
  611. }
  612. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  613. // const req: CrowiRequest = context.req as CrowiRequest;
  614. // const { crowi } = req;
  615. // const UserModel = crowi.model('User');
  616. // if (isUserPage(props.currentPagePath)) {
  617. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  618. // if (user != null) {
  619. // props.pageUser = JSON.stringify(user.toObject());
  620. // }
  621. // }
  622. // }
  623. function injectServerConfigurations(
  624. context: GetServerSidePropsContext,
  625. props: Props,
  626. ): void {
  627. const req: CrowiRequest = context.req as CrowiRequest;
  628. const { crowi } = req;
  629. const {
  630. configManager,
  631. searchService,
  632. aclService,
  633. fileUploadService,
  634. slackIntegrationService,
  635. passportService,
  636. } = crowi;
  637. props.aiEnabled = configManager.getConfig('app:aiEnabled');
  638. props.limitLearnablePageCountPerAssistant = configManager.getConfig(
  639. 'openai:limitLearnablePageCountPerAssistant',
  640. );
  641. props.isUsersHomepageDeletionEnabled = configManager.getConfig(
  642. 'security:user-homepage-deletion:isEnabled',
  643. );
  644. props.isSearchServiceConfigured = searchService.isConfigured;
  645. props.isSearchServiceReachable = searchService.isReachable;
  646. props.isSearchScopeChildrenAsDefault = configManager.getConfig(
  647. 'customize:isSearchScopeChildrenAsDefault',
  648. );
  649. props.elasticsearchMaxBodyLengthToIndex = configManager.getConfig(
  650. 'app:elasticsearchMaxBodyLengthToIndex',
  651. );
  652. props.isRomUserAllowedToComment = configManager.getConfig(
  653. 'security:isRomUserAllowedToComment',
  654. );
  655. props.isSlackConfigured = slackIntegrationService.isSlackConfigured;
  656. // props.isMailerSetup = mailService.isMailerSetup;
  657. props.isAclEnabled = aclService.isAclEnabled();
  658. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  659. props.drawioUri = configManager.getConfig('app:drawioUri');
  660. // props.highlightJsStyle = configManager.getConfig('customize:highlightJsStyle');
  661. props.isAllReplyShown = configManager.getConfig('customize:isAllReplyShown');
  662. props.showPageSideAuthors = configManager.getConfig(
  663. 'customize:showPageSideAuthors',
  664. );
  665. props.isContainerFluid = configManager.getConfig(
  666. 'customize:isContainerFluid',
  667. );
  668. props.isEnabledStaleNotification = configManager.getConfig(
  669. 'customize:isEnabledStaleNotification',
  670. );
  671. props.disableLinkSharing = configManager.getConfig(
  672. 'security:disableLinkSharing',
  673. );
  674. props.isUploadAllFileAllowed = fileUploadService.getFileUploadEnabled();
  675. props.isUploadEnabled = fileUploadService.getIsUploadable();
  676. // TODO: remove growiCloudUri condition when bulk export can be relased for GROWI.cloud (https://redmine.weseek.co.jp/issues/163220)
  677. props.isBulkExportPagesEnabled =
  678. configManager.getConfig('app:isBulkExportPagesEnabled') &&
  679. configManager.getConfig('app:growiCloudUri') == null;
  680. props.isPdfBulkExportEnabled =
  681. configManager.getConfig('app:pageBulkExportPdfConverterUri') != null;
  682. props.isLocalAccountRegistrationEnabled =
  683. passportService.isLocalStrategySetup &&
  684. configManager.getConfig('security:registrationMode') !==
  685. RegistrationMode.CLOSED;
  686. props.adminPreferredIndentSize = configManager.getConfig(
  687. 'markdown:adminPreferredIndentSize',
  688. );
  689. props.isIndentSizeForced = configManager.getConfig(
  690. 'markdown:isIndentSizeForced',
  691. );
  692. props.isEnabledAttachTitleHeader = configManager.getConfig(
  693. 'customize:isEnabledAttachTitleHeader',
  694. );
  695. props.sidebarConfig = {
  696. isSidebarCollapsedMode: configManager.getConfig(
  697. 'customize:isSidebarCollapsedMode',
  698. ),
  699. isSidebarClosedAtDockMode: configManager.getConfig(
  700. 'customize:isSidebarClosedAtDockMode',
  701. ),
  702. };
  703. props.rendererConfig = {
  704. isEnabledLinebreaks: configManager.getConfig(
  705. 'markdown:isEnabledLinebreaks',
  706. ),
  707. isEnabledLinebreaksInComments: configManager.getConfig(
  708. 'markdown:isEnabledLinebreaksInComments',
  709. ),
  710. isEnabledMarp: configManager.getConfig('customize:isEnabledMarp'),
  711. adminPreferredIndentSize: configManager.getConfig(
  712. 'markdown:adminPreferredIndentSize',
  713. ),
  714. isIndentSizeForced: configManager.getConfig('markdown:isIndentSizeForced'),
  715. drawioUri: configManager.getConfig('app:drawioUri'),
  716. plantumlUri: configManager.getConfig('app:plantumlUri'),
  717. // XSS Options
  718. isEnabledXssPrevention: configManager.getConfig(
  719. 'markdown:rehypeSanitize:isEnabledPrevention',
  720. ),
  721. sanitizeType: configManager.getConfig('markdown:rehypeSanitize:option'),
  722. customTagWhitelist: configManager.getConfig(
  723. 'markdown:rehypeSanitize:tagNames',
  724. ),
  725. customAttrWhitelist:
  726. configManager.getConfig('markdown:rehypeSanitize:attributes') != null
  727. ? JSON.parse(
  728. configManager.getConfig('markdown:rehypeSanitize:attributes'),
  729. )
  730. : undefined,
  731. highlightJsStyleBorder: configManager.getConfig(
  732. 'customize:highlightJsStyleBorder',
  733. ),
  734. };
  735. props.ssrMaxRevisionBodyLength = configManager.getConfig(
  736. 'app:ssrMaxRevisionBodyLength',
  737. );
  738. }
  739. /**
  740. * for Server Side Translations
  741. * @param context
  742. * @param props
  743. * @param namespacesRequired
  744. */
  745. async function injectNextI18NextConfigurations(
  746. context: GetServerSidePropsContext,
  747. props: Props,
  748. namespacesRequired?: string[] | undefined,
  749. ): Promise<void> {
  750. const nextI18NextConfig = await getNextI18NextConfig(
  751. serverSideTranslations,
  752. context,
  753. namespacesRequired,
  754. );
  755. props._nextI18Next = nextI18NextConfig._nextI18Next;
  756. }
  757. const getAction = (props: Props): SupportedActionType => {
  758. if (props.isNotCreatable) {
  759. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  760. }
  761. if (props.isForbidden) {
  762. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  763. }
  764. if (props.isNotFound) {
  765. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  766. }
  767. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  768. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  769. }
  770. return SupportedAction.ACTION_PAGE_VIEW;
  771. };
  772. export const getServerSideProps: GetServerSideProps = async (
  773. context: GetServerSidePropsContext,
  774. ) => {
  775. const req = context.req as CrowiRequest;
  776. const { user } = req;
  777. const result = await getServerSideCommonProps(context);
  778. // check for presence
  779. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  780. if (!('props' in result)) {
  781. throw new Error('invalid getSSP result');
  782. }
  783. const props: Props = result.props as Props;
  784. if (props.redirectDestination != null) {
  785. return {
  786. redirect: {
  787. permanent: false,
  788. destination: props.redirectDestination,
  789. },
  790. };
  791. }
  792. if (user != null) {
  793. props.currentUser = user.toObject();
  794. }
  795. try {
  796. await injectPageData(context, props);
  797. } catch (err) {
  798. if (err instanceof MultiplePagesHitsError) {
  799. props.isIdenticalPathPage = true;
  800. } else {
  801. throw err;
  802. }
  803. }
  804. await injectRoutingInformation(context, props);
  805. injectServerConfigurations(context, props);
  806. await injectNextI18NextConfigurations(context, props, ['translation']);
  807. addActivity(context, getAction(props));
  808. return {
  809. props,
  810. };
  811. };
  812. export default Page;